<template>

	<div class="mb-4 flex justify-between items-center">
		<el-button
			type="primary"
			class="action-btn"
			@click="add()"
		>
			<i class="el-icon-plus mr-2" />新建文件
		</el-button>

	<div 	align="right">
		<el-button
			type="primary"
			class="action-btn"
			@click="getPage"
		>
			<i class="el-icon-search mr-2" />查询
		</el-button>
	</div>
	</div>

	<!-- 数据表格 -->
	<el-table :data="paginatedData" border>
		<el-table-column prop="fileName" label="文件名称"/>
		<el-table-column prop="fileUrl" label="文件地址" width="220" align="center">
			<template #default="{row}">
				<div class="file-link">
					<!-- 图片类型展示预览 -->
					<el-image
						v-if="isImageType(row.fileUrl)"
						style="width: 80px; height: 40px; cursor: pointer"
						:src="row.fileUrl"
						:preview-src-list="[row.fileUrl]"
						fit="contain"
						close-on-click-modal
						preview-teleported
						:z-index="9999"
					>
						<template #error>
							<div class="text-gray-400">预览加载失败</div>
						</template>
					</el-image>

					<!-- 非图片类型展示跳转链接 -->
					<a
						v-else
						:href="row.fileUrl"
						target="_blank"
						class="text-blue-600 hover:text-blue-800 truncate"
					>
						{{ getFileName(row.fileUrl) }}
						<el-tag
							size="mini"
							:type="getFileTagType(row.fileUrl)"
							class="ml-2"
						>
							{{ getFileExtension(row.fileUrl) }}
						</el-tag>
					</a>
				</div>
			</template>
		</el-table-column>
		<el-table-column prop="pusherName" label="推送人"/>
		<el-table-column label="接收人">
			<template #default="{row}">
				<el-button type="text" @click="openRecipientsDialog(row)">
					{{ formatRecipientsName(row.oaDocumentFollowupUserParamList) }}
				</el-button>
			</template>
		</el-table-column>
		<el-table-column prop="pushTime" label="推送时间"/>
		<el-table-column label="操作" width="150">
			<template #default="{row}">
				<el-button size="small" @click="openDialog(row)">编辑Test</el-button>
				<el-button size="small" @click="edit(row)">编辑</el-button>
				<el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 接收人弹窗 -->
	<el-dialog title="接收人信息" v-model="recipientsDialogVisible" width="600px">
		<el-table :data="recipientsData" border>
			<el-table-column prop="approverName" label="接收人名称"/>
			<el-table-column label="消息状态" prop="messageStatus">
				<template #default="{row}">
				<span
					v-if="row.messageStatus === '0'"
					:style="{ color: 'red' }">未读</span>
					<span
						v-else-if="row.messageStatus === '1'"
						:style="{ color: 'green' }">已读</span>
					<span
						v-else-if="row.messageStatus === '2'"
						:style="{ color: 'blue' }">收到</span>
				</template>
			</el-table-column>
		</el-table>
	</el-dialog>

	<!-- 分页组件 -->
	<el-pagination
		v-model:current-page="currentPage"
		:page-size="pageSize"
		layout="total, prev, pager, next"
		:total="total"
		class="mt-4"
		@current-change="currentChange"
	/>

	<!-- 表单弹窗 -->
	<el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
		<el-form :model="formData" label-width="100px" ref="formRef" :rules="rules">
			<el-form-item label="附件上传" prop="file">
				<el-upload
					:action="action"
					:file-list="fileList"
					:before-upload="beforeUpload"
					:on-success="handleSuccess"
				>
					<el-button type="primary">点击上传</el-button>
					<template #tip>
						<div class="el-upload__tip">支持格式：doc/pdf/图片/视频（单文件≤50MB）</div>
					</template>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="dialogTitle === '编辑文件贯彻' " label="文件名称" prop="fileName">
				<el-input v-model="formData.fileName" placeholder="请输入文件名称" />
			</el-form-item>
			<el-form-item label="审批人">
				<multi-select-personnel-module ref="multiSelectPersonnelModule" :mode="true"
											   @success="onApproverSelected"></multi-select-personnel-module>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="dialogVisible = false">取消</el-button>
			<el-button type="primary" @click="submitForm">提交</el-button>
		</template>
	</el-dialog>
</template>




<script>
import multiSelectPersonnelModule from '@/views/module/selectUserDialogGetUserDeptId.vue';
import {FINANCE_CODES} from '@/config/statusCodes'



export default {
	components: {
		multiSelectPersonnelModule,
	},
	data() {
		return {
			paginatedData: [], // 初始化数据需要移到外部

			action: '/capi/get/uploadFileByCode?code=' + FINANCE_CODES.DOCUMENT_FOLLOW_UP,
			total: 0,
			currentPage: 1,
			pageSize: 15,
			dialogVisible: false,
			dialogTitle: '',
			userInfo: {},
			formData: {
				id: null,
				leader: '',
				file: null,
				fileUrl: '',
				oaDocumentFollowupUserParamList: []
			},
			fileList: [],
			users: [],
			rules: {
				leader: [{required: true, message: '请选择负责人'}],
				fileName: [{required: true, message: '请填写文件名称'}],
				recipientsId: [{type: 'array', required: true, message: '至少选择1位必看人员'}],
				file: [{required: true, message: '请上传文件'}]
			},
			recipientsDialogVisible: false,
			recipientsData: [],
		}
	},
	computed: {},
	mounted() {
		this.getUsers();
		this.userInfo = this.$TOOL.data.get("USER_INFO");
		console.log('userInfo', this.userInfo)
		this.getPage();
	},
	methods: {
		onApproverSelected(selectedUsers) {
			console.log('selectedUsers:', selectedUsers);
			if (selectedUsers && selectedUsers.length > 0) {
				this.formData.oaDocumentFollowupUserParamList = selectedUsers.map(user => {
					return {
						recipientId: user.userId,
						recipientName: user.userName,
					};
				});
			}
			console.log('this.ApproversFormData', this.formData);
		},
		currentChange(val) {
			this.currentPage = val;
			console.log('currentPage', this.currentPage)
			this.getPage()
		},
		getUsers() {
			this.$API.office.documentationFollowThrough.getUserInfoAll.get().then(res => {
				this.users = res.data;
				console.log('users', this.users)
			}).catch(err => {
				this.$message.error('获取用户失败')
			})
		},
		getPage() {
			this.$API.office.documentationFollowThrough.getByPusherId.get(
				{
					pusherId: this.userInfo.id,
					page: this.currentPage,
					pageSize: this.pageSize
				}
			).then(res => {
				console.log('res.data.list', res.data.list)
				this.paginatedData = res.data.list;
				this.total = parseInt(res.data.total, 10); // 将字符串转换为数字
				console.log('paginatedData', this.paginatedData)
			}).catch(err => {
				this.$message.error('分页失败')
			})
		},
		getRecipientsPage() {
			this.$API.office.documentationFollowThrough.getByRecipients.get(
				{
					option1: this.userInfo.id,
					recipientsId: this.userInfo.id,
				}
			).then(res => {
				console.log('res.data.list', res.data.list)
				this.paginatedData = res.data.list;
			}).catch(err => {
				this.$message.error('分页失败')
			})
		},
		beforeUpload(file) {
			const isLt50M = file.size / 1024 / 1024 < 50
			if (!isLt50M) {
				this.$message.error('文件大小不能超过50MB!')
				return false
			}
			this.formData.fileName = file.name
			console.log('beforeUpload', file)
			return true
		},
		handleSuccess(response, file) {
			console.log('response', response)
			console.log('response.url', response.redirect)
			this.formData.fileUrl = response.redirect
			this.fileList = [{name: file.name, url: response.redirect}];
		},
		add(){
			this.formData = {};
			this.dialogTitle = '添加文件贯彻';
			this.dialogVisible = true;
		},
		openDialog(row) {
		   console.log('row', row);
			// this.dialogTitle = '编辑文件贯彻';
			// 	if (row.fileUrl) {
			//
			// 		this.formData.fileUrl = row.fileUrl;
			// 		this.fileList = [{name: row.fileName, url: row.fileUrl}];
			// 	}
			// this.dialogVisible = true;
			// console.log('row1',row)
			// // Object.assign(this.formData, row);
			// this.formData = row;
			// console.log('row2', this.formData);
		},
		editTest(){
			console.log('row', 123123123);
		},
		edit(row) {
			console.log('row', JSON.parse(JSON.stringify(row))); // 这样可以打印完整的对象
			this.dialogTitle = '编辑文件贯彻';
			if (row.fileUrl) {
				this.formData.fileUrl = row.fileUrl;
				this.fileList = [{name: row.fileName, url: row.fileUrl}];
			}
			this.dialogVisible = true;
			console.log('row1', JSON.parse(JSON.stringify(row)));
			this.formData = {...row}; // 使用展开运算符创建新对象
			console.log('row2', JSON.parse(JSON.stringify(this.formData)));
		},
		openRecipientsDialog(row) {
			this.$API.office.documentationFollowThrough.getByRecipientsIdAndId.get({
				pusherId: this.userInfo.id,
				id: row.id
			}).then(res => {
				console.log('res.data.list', res.data)
				this.recipientsData = res.data;
				console.log('this.recipientsData', this.recipientsData)
				this.recipientsDialogVisible = true;
			}).catch(err => {
				this.$message.error('获取接收人状态信息失败');
			});
		},
		submitForm() {
			// Enhanced validation
			if (!this.fileList || this.fileList.length === 0) {
				this.$message.error('请上传至少一个文件')
				return
			}

			// 校验是否选择了有效的必看人员
			if (!Array.isArray(this.formData.oaDocumentFollowupUserParamList) ||
				this.formData.oaDocumentFollowupUserParamList.length === 0) {
				this.$message.error('请至少选择一位有效的必看人员')
				return
			}

			let params = {
				pusherId: this.userInfo.id,
				oaDocumentFollowupUserParamList: this.formData.oaDocumentFollowupUserParamList,
				fileUrl: this.formData.fileUrl,
				fileName: this.formData.fileName
			};
			console.log('formData', params)
			if (this.formData.id) {
				params.id = this.formData.id
				this.$API.office.documentationFollowThrough.update.postPro(params).then(res => {
					this.getPage();
				})
					.catch(err => {
						this.$message.error('编辑失败')
					})
			} else {
				this.$API.office.documentationFollowThrough.add.postPro(params).then(res => {
					this.getPage();
				})
					.catch(err => {
						this.$message.error('添加失败')
					})
			}

			this.dialogVisible = false
			this.$message.success('操作成功')
		},
		handleDelete(id) {
			console.log('id', id)
			this.$confirm('确认删除该记录？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$API.office.documentationFollowThrough.deleteById.del({id: id}).then(res => {
					this.getPage();
					this.$message.success('删除成功')
				}).catch(err => {
					this.$message.success('删除失败')
				})
			})
		},
		// 获取文件扩展名（带MIME类型校验更准确）
		getFileExtension(url) {
			const ext = url.split('.').pop().toLowerCase()
			const mimeMap = {
				png: 'image/png',
				jpg: 'image/jpeg',
				jpeg: 'image/jpeg',
				gif: 'image/gif',
				pdf: 'application/pdf',
				doc: 'application/msword',
				docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
			}
			return mimeMap[ext] ? ext : 'file'
		},

		// 判断是否为图片类型（根据MIME类型）
		isImageType(url) {
			const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp']
			return imageTypes.includes(this.getFileExtension(url))
		},

		// 获取带后缀的文件名
		getFileName(url) {
			return url.split('/').pop().substring(0, 20) + (url.length > 20 ? '...' : '')
		},

		// 获取文件标签样式类型
		getFileTagType(url) {
			const typeMap = {
				pdf: 'danger',
				doc: 'primary',
				docx: 'primary',
				xls: 'warning',
				xlsx: 'warning',
				ppt: 'success',
				pptx: 'success'
			}
			return typeMap[this.getFileExtension(url)] || 'info'
		},
		// 格式化接收人名称
		formatRecipientsNameTest(oaDocumentFollowupUserParamList) {
			/**
			 *       "oaDocumentFollowupUserParamList": [
			 *                     {
			 *                         "recipientId": "652",
			 *                         "recipientName": "阮鲜珑"
			 *                     },
			 *                     {
			 *                         "recipientId": "653",
			 *                         "recipientName": "康辰博"
			 *                     },
			 *                     {
			 *                         "recipientId": "654",
			 *                         "recipientName": "章"
			 *                     },
			 *                     {
			 *                         "recipientId": "655",
			 *                         "recipientName": "340406201811140613"
			 *                     }
			 *                 ],
			 */
			 //todo result = "阮鲜珑、康辰博、章、340406201811140613"
           let result =  result = "阮鲜珑、康辰博、章、340406201811140613"
			return result;
		},formatRecipientsName(oaDocumentFollowupUserParamList) {
			// 安全处理：如果参数未定义或不是数组，返回空字符串
			if (!Array.isArray(oaDocumentFollowupUserParamList)) {
				return '';
			}

			// 过滤掉无效条目并提取名称
			const names = oaDocumentFollowupUserParamList
				.filter(item => item && item.recipientName) // 过滤掉null/undefined条目和没有recipientName的条目
				.map(item => item.recipientName); // 提取名称

			// 如果没有有效名称，返回默认文本
			if (names.length === 0) {
				return '无接收人';
			}

			// 用中文顿号连接名称
			let result = names.join('、');

			// 如果顿号超过5个（即名称超过6个），截断并添加省略号
			const commaCount = (result.match(/、/g) || []).length;
			if (commaCount > 5) {
				// 取前6个名称
				const firstSixNames = names.slice(0, 6).join('、');
				result = `${firstSixNames}等${names.length}人`;
			}

			return result;
		}
	}
}

</script>


<style scoped>
/* 添加样式 */
.file-link {
	@apply flex items-center;
}

.file-thumbnail {
	@apply w-16 h-16 rounded cursor-pointer shadow hover:shadow-md transition-all;
}

.el-image__error {
	@apply flex items-center justify-center bg-gray-100;
}

.el-tag {
	@apply transform scale-90;
}

/* 在style区块添加 */
.recipients-button {
	white-space: pre-line; /* 允许换行符生效 */
	word-break: break-all; /* 处理超长单词换行 */
	text-align: left; /* 保持左对齐 */
	line-height: 1.5; /* 优化行间距 */
	max-width: 200px; /* 限制按钮宽度 */
}
</style>

